import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { Task } from '../../pages/home/task';

let s='https://api2.bmob.cn/1/classes/ToDoList/';


@Injectable()
export class HttpDataProvider {

  //private readonly baseUrl:string="";
  private readonly httpOptions:Object={
    headers:new HttpHeaders({
      'X-Bmob-Application-Id':'68e7c80b78269f4760ea52a5ee3e0b7b',
      'X-Bmob-REST-API-Key':'8715344363529ed6959aea83131e720f',
      'Content-Type': 'application/json',
    })
  };

  constructor(public http: HttpClient) {
    console.log('获取HTTP数据服务加载');
  }
  /**
   * 获取待办事项列表
   * @returns{Observable<Task[]>} 待办事项列表数据集合
   */
  getTaskList():Observable<Task[]>{
    return this.http.get<Task[]>('https://api2.bmob.cn/1/classes/ToDoList',
    this.httpOptions).map(data=>data["results"]);
  }
  /**
   * 获取指定代办事项
   * @param objectId 
   * @returns{Observable<Task>}待办事项
   */
  getTask(objectId:string):Observable<Task>{
    return this.http.get<Task>(s+objectId,
    this.httpOptions);
  };
  /**
   * 新增指定的待办事项
   * @param task 
   * @returns{Observable<Task>}响应结果
   */
  addTask(task:Task):Observable<Task>{
    let _task={title:task.title,status:task.status,description:task.description};
    return this.http.post<Task>('https://api2.bmob.cn/1/classes/ToDoList/',
    _task,this.httpOptions);
  }
  /**
   * 更新指定的待办事项
   * @param task 
   * @returns{Observable<Task>}响应结果
   */
  updateTask(task:Task): Observable<Task>{
    let _task={title:task.title,status:task.status,description:task.description};
    return this.http.put<Task>(s+task.objectId,
    _task,this.httpOptions);
  }
  /**
   * 删除指定的待办事项
   * @param task 
   * @returns{Observable<Task>}响应结果
   */
  deleteTask(task:Task): Observable<{}>{
    return this.http.delete(s+task.objectId,this.httpOptions);
  }
}
